package com.supor.aiot.home.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.baseconfig.common.utils.ThreadUtils;
import com.supor.aiot.common.utils.AnimationUtil;
import com.supor.aiot.home.R;

import java.lang.ref.WeakReference;

import pl.droidsonroids.gif.GifImageView;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: PopUtils <br>
 * 作者: lei <br>
 * 日期: 2020/12/28 <br>
 */
public class PopUtils {

    static PopupWindow popupWindow;
    Handler handler;
    private WeakReference<Activity> activityReference;

    private static volatile PopUtils instance;
    private float alpha;
    int duration = 500;
    int sleepTime = duration / 100;
    ImageView ivFinish;
    TextView tvDialogText;
    TextView tvDialogTip;
    TextView tvDialogTip1;
    Button popCancel;
    GifImageView gifIv;

    public static PopUtils getInstance() {
        if (instance == null) {
            instance = new PopUtils();
        }
        return instance;
    }

    private PopUtils() {
    }

    public void initNFCPop(Activity activity) {
        activityReference = new WeakReference<>(activity);
        handler = new Handler(activity.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    AnimationUtil.backgroundAlpha(activityReference.get(), (float) msg.obj);
                }
            }
        };
        popupWindow = new PopupWindow();
        View view = LayoutInflater.from(activity).inflate(R.layout.pop_nfc, null);
        popupWindow.setContentView(view);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.setFocusable(false);// 解决点击view重新打开popwindow的问题
        popupWindow.setOutsideTouchable(false);// 点击外部popupwindow消失
        popupWindow.setAnimationStyle(R.style.popup_window_anim);

        ivFinish = view.findViewById(R.id.iv_finish);
        gifIv = view.findViewById(R.id.gif_iv);
        tvDialogText = view.findViewById(R.id.tv_dialog_text);
        tvDialogTip = view.findViewById(R.id.tv_dialog_tip);
        tvDialogTip1 = view.findViewById(R.id.tv_dialog_tip1);
        tvDialogTip1.setVisibility(View.GONE);
        popCancel = view.findViewById(R.id.pop_cancel);

        popCancel.setOnClickListener(v -> popupWindow.dismiss());
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        // 退出popupWindow时取消暗背景
        popupWindow.setOnDismissListener(() -> ThreadUtils.execute(() -> {
            while (alpha < 1f) {
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                alpha += 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        }));
    }

    public void showNFCPop(Activity activity, View rootView) {
        if (popupWindow == null) {
            initNFCPop(activity);
        } else {
            ivFinish.setVisibility(View.GONE);
            tvDialogText.setVisibility(View.VISIBLE);
            tvDialogTip.setText(R.string.nfc_dialog_tip);
            tvDialogTip.setTextSize(TypedValue.COMPLEX_UNIT_PX, activity.getResources().getDimensionPixelSize(R.dimen.sp_16));
            tvDialogTip.setTextColor(activity.getResources().getColor(R.color.content_default));
            tvDialogTip1.setVisibility(View.GONE);
            ivFinish.setVisibility(View.INVISIBLE);
            gifIv.setVisibility(View.VISIBLE);
            popCancel.setVisibility(View.VISIBLE);
        }
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        alpha = 1f;
        ThreadUtils.execute(() -> {
            while (alpha > 0.5f) {
                try {
                    // 根据弹出动画时间和减少的透明度计算时间
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                // 每次减少0.005，精度越高，变暗的效果越流畅
                alpha -= 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        });
    }

    public boolean isNFCPopShow() {
        return popupWindow != null && popupWindow.isShowing();
    }

    public void touchSuccess() {
        touchSuccess(null);
    }

    public void touchSuccess(String tips) {
        touchSuccess(R.string.nfc_operate_success, tips);
    }

    public void touchSuccess(int tipId, String tip1) {
        ivFinish.setVisibility(View.VISIBLE);
        tvDialogText.setVisibility(View.INVISIBLE);
        tvDialogTip.setText(tipId);
        tvDialogTip.setTextSize(TypedValue.COMPLEX_UNIT_PX, activityReference.get().getResources().getDimensionPixelSize(R.dimen.sp_16));
        tvDialogTip.setTextColor(activityReference.get().getResources().getColor(R.color.content_default));
        gifIv.setVisibility(View.INVISIBLE);
        tvDialogTip1.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(tip1)) {
            tvDialogTip1.setText(tip1);
        }
        popCancel.setVisibility(View.INVISIBLE);
        handler.postDelayed(this::dismissNFCPop, 2500);
    }

    public void dismissNFCPop() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }
}
